package com.rookie.tool.module.util.ai.util;


import com.rookie.tool.module.util.ai.constant.CommonConstant;
import com.rookie.tool.module.util.ai.entity.BaiDuToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

/**
 * 人脸相关
 *
 * @author rookie
 */
@Slf4j
public class TokenUtils {
    public static RestTemplate restTemplate = new RestTemplate();

    /**
     * 获取系统配置key的token
     * @return
     */
    public static BaiDuToken getAuth() {
        return getAuth(CommonConstant.BAI_DU_CLIENT_ID, CommonConstant.BAI_DU_CLIENT_ID);
    }

    public static String getToken(){
        BaiDuToken auth = getAuth();
        if (auth != null){
            return auth.getAccessToken();
        }else{
            return "";
        }
    }

    public static String getToken(String ak, String sk){
        BaiDuToken auth = getAuth(ak,sk);
        if (auth != null){
            return auth.getAccessToken();
        }else{
            return "";
        }
    }

    /**
     * 获取指定key的token
     */
    public static BaiDuToken getAuth(String ak, String sk) {
        // 获取token地址
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + ak
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + sk;
        BaiDuToken forObject = null;
        try {
            forObject = restTemplate.getForObject(getAccessTokenUrl, BaiDuToken.class);
        } catch (RestClientException e) {
            log.error("获取百度token失败:{}",e.getMessage());
        }
        return forObject;
    }

}
